from fastmcp import FastMCP
from pydantic import BaseModel
import os
import requests
import json

mcp = FastMCP("walkerAPI-mcp-server")

@mcp.tool()
def get_apifox_json_prompt(url_list: str,classPath: str) -> str:
    """
    传递问题涉及的所有接口，返回生成导入到apifox的JSON格式的Prompt
    参数:
        url_list (str): 需要导入的接口url列表，多个url用逗号分隔
        classPath (str): 类路径，用于指定接口的类路径
    返回:
        str: 生成导入到apifox的JSON格式的Prompt
    """
    template_path = os.path.join(os.path.dirname(__file__), "apifox_prompt_template.txt")
    with open(template_path, "r", encoding="utf-8") as f:
        prompt_template = f.read()
    return prompt_template % (url_list, classPath)

@mcp.tool()
def save_json_content_to_file(json_content: str) -> str:
    """
    接收Apifox的JSON内容，并且把JSON另存为文件后，调用apifox导入接口。
    参数:
        json_content (str): 需要保存的json内容
    返回:
        str: 导入结果
    环境变量:
        UPLOAD_BASE_URL: 上传文件的API接口地址，默认为http://localhost:8080
        APIFOX_PROJECT_ID: Apifox项目ID
        APIFOX_ACCESS_TOKEN: Apifox访问令牌
    """

    api_url = os.environ.get("UPLOAD_BASE_URL", "http://localhost:8080")
    save_json_api_url = api_url + "/file/saveJSON"

    try:
        response = requests.post(
            save_json_api_url,
            json={"content": json_content},
            timeout=10
        )
        response.raise_for_status()
        data = response.json()
        # 假设返回值格式为 {"url": "..."}

        json_file_url = data.get("url", "未获取到url")

        # 调用apifox导入接口
        project_id = os.environ.get("APIFOX_PROJECT_ID")
        access_token = os.environ.get("APIFOX_ACCESS_TOKEN")
        if not project_id or not access_token:
            return json.dumps({"error": "缺少APIFOX_PROJECT_ID或APIFOX_ACCESS_TOKEN环境变量"}, ensure_ascii=False)
            
        apifox_url = f"https://api.apifox.com/v1/projects/{project_id}/import-openapi"
        headers = {
            "X-Apifox-Api-Version": "2024-03-28",
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json"
        }
        payload = {
            "input": {"url": f"{api_url}{json_file_url}"},
            "options": {
                "endpointOverwriteBehavior": "OVERWRITE_EXISTING",
                "schemaOverwriteBehavior": "KEEP_EXISTING",
                "updateFolderOfChangedEndpoint": True,
                "prependBasePath": True
            }
        }

        try:
            apifox_resp = requests.post(apifox_url, headers=headers, json=payload, timeout=20)
            apifox_resp.raise_for_status()
            apifox_result = apifox_resp.json()
        except Exception as e:
            apifox_result = f"Apifox导入失败: {e}"

        
        # 返回json_file_url和apifox导入结果
        return json.dumps({"json_file_url": json_file_url, "apifox_result": apifox_result}, ensure_ascii=False)
    except Exception as e:
        return f"请求失败: {e}"

# 本地启动方式
if __name__ == "__main__":
    mcp.run()